<template>
    <div class="home-view">
        <el-container>
            <el-header height="80">
                <div class="header-content">
                    <h1>电影数据分析系统</h1>
                    <div class="header-right">
                        <el-button type="primary" @click="showAnalysisView = !showAnalysisView">
                            {{ showAnalysisView ? "返回电影列表" : "查看深度分析" }}
                        </el-button>
                    </div>
                </div>
            </el-header>

            <el-main>
                <div v-if="!showAnalysisView" class="movie-list-view">
                    <div class="filter-panel">
                        <el-card class="filter-card">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="电影类型">
                                        <el-select
                                            v-model="selectedGenres"
                                            multiple
                                            placeholder="选择类型"
                                            style="width: 100%"
                                            collapse-tags
                                        >
                                            <el-option
                                                v-for="genre in genres"
                                                :key="genre"
                                                :label="genre"
                                                :value="genre"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="8">
                                    <el-form-item label="上映年份">
                                        <el-slider
                                            v-model="yearRange"
                                            range
                                            :min="1990"
                                            :max="2023"
                                            :marks="{ 1990: '1990', 2000: '2000', 2010: '2010', 2023: '2023' }"
                                        />
                                    </el-form-item>
                                </el-col>

                                <el-col :span="8">
                                    <el-form-item label="最低评分">
                                        <el-slider
                                            v-model="minRating"
                                            :min="8"
                                            :max="10"
                                            :step="0.1"
                                            :marks="{ 8: '8.0', 9: '9.0', 10: '10.0' }"
                                        />
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="国家/地区">
                                        <el-select
                                            v-model="selectedCountries"
                                            multiple
                                            placeholder="选择国家/地区"
                                            style="width: 100%"
                                            collapse-tags
                                        >
                                            <el-option
                                                v-for="country in countries"
                                                :key="country"
                                                :label="country"
                                                :value="country"
                                            />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row>
                                <el-col :span="24" style="text-align: right">
                                    <el-button type="primary" @click="resetFilters">重置筛选</el-button>
                                </el-col>
                            </el-row>
                        </el-card>
                    </div>

                    <div class="movie-stats">
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-card shadow="hover" class="stat-card">
                                    <div class="stat-number">{{ filteredMovies.length }}</div>
                                    <div class="stat-label">符合条件的电影</div>
                                </el-card>
                            </el-col>

                            <el-col :span="6">
                                <el-card shadow="hover" class="stat-card">
                                    <div class="stat-number">{{ averageRating.toFixed(1) }}</div>
                                    <div class="stat-label">平均评分</div>
                                </el-card>
                            </el-col>

                            <el-col :span="6">
                                <el-card shadow="hover" class="stat-card">
                                    <div class="stat-number">{{ topGenre }}</div>
                                    <div class="stat-label">最常见类型</div>
                                </el-card>
                            </el-col>

                            <el-col :span="6">
                                <el-card shadow="hover" class="stat-card">
                                    <div class="stat-number">{{ movieCountByYear }}</div>
                                    <div class="stat-label">TOP年份 ({{ topYear }})</div>
                                </el-card>
                            </el-col>
                        </el-row>
                    </div>

                    <MovieTable :movies="filteredMovies" />
                </div>

                <div v-else class="analysis-view">
                    <el-row :gutter="20">
                        <el-col :span="16">
                            <DirectorChart :data="directorData" />
                        </el-col>
                        <el-col :span="8">
                            <Predictor :genres="genres" :directors="directors" :movie-data="movies" />
                        </el-col>
                    </el-row>

                    <el-row :gutter="20" style="margin-top: 20px">
                        <el-col :span="24">
                            <InsightPanel :movie-data="movies" />
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-card class="genre-analysis">
                                <template #header>
                                    <div class="card-header">
                                        <span>类型分析</span>
                                    </div>
                                </template>
                                <div class="genre-chart" ref="genreChartRef"></div>
                            </el-card>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="24">
                            <el-card class="year-analysis">
                                <template #header>
                                    <div class="card-header">
                                        <span>年代分析</span>
                                    </div>
                                </template>
                                <div class="year-chart" ref="yearChartRef"></div>
                            </el-card>
                        </el-col>
                    </el-row>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script>
import { ref, computed, onMounted, watch, nextTick } from "vue";
import MovieTable from "@/components/MovieTable.vue";
import DirectorChart from "@/components/DirectorChart.vue";
import Predictor from "@/components/Predictor.vue";
import InsightPanel from "@/components/InsightPanel.vue";
import movieData from "@/data/movies.json";
import * as echarts from "echarts";

export default {
    name: "HomeView",
    components: { MovieTable, DirectorChart, Predictor, InsightPanel },
    setup() {
        // 确保加载所有电影数据
        const movies = ref([]);

        // 在组件挂载时加载数据，确保正确处理
        onMounted(() => {
            console.log(`加载了 ${movieData.length} 条电影数据`);
            movies.value = movieData;
        });

        const selectedGenres = ref([]);
        const yearRange = ref([1990, 2023]);
        const minRating = ref(0.0);
        const selectedCountries = ref([]);
        const showAnalysisView = ref(false);

        const genreChartRef = ref(null);
        const yearChartRef = ref(null);

        // 所有类型列表
        const genres = computed(() => {
            const allGenres = new Set();
            movies.value.forEach((movie) => {
                if (movie.genres) {
                    movie.genres.forEach((genre) => allGenres.add(genre));
                }
            });
            return [...allGenres].sort();
        });

        // 所有国家/地区列表
        const countries = computed(() => {
            const allCountries = new Set();
            movies.value.forEach((movie) => {
                if (movie.countries) {
                    movie.countries.forEach((country) => allCountries.add(country));
                }
            });
            return [...allCountries].sort();
        });

        // 所有导演列表
        const directors = computed(() => {
            const allDirectors = new Set();
            movies.value.forEach((movie) => {
                if (movie.directors) {
                    movie.directors.forEach((director) => allDirectors.add(director));
                }
            });
            return [...allDirectors].sort();
        });

        // 筛选后的电影
        const filteredMovies = computed(() => {
            return movies.value.filter((movie) => {
                // 类型筛选
                const genreMatch =
                    selectedGenres.value.length === 0 ||
                    selectedGenres.value.some((g) => movie.genres && movie.genres.includes(g));

                // 年份筛选 - 确保正确处理年份格式
                let year = movie.year;
                if (typeof year === "string") {
                    year = parseInt(year, 10);
                }
                const yearMatch = !isNaN(year) && year >= yearRange.value[0] && year <= yearRange.value[1];

                // 评分筛选 - 确保正确处理评分格式
                let rating = movie.rating;
                if (typeof rating === "string") {
                    rating = parseFloat(rating);
                }
                const ratingMatch = !isNaN(rating) && rating >= minRating.value;

                // 国家筛选
                const countryMatch =
                    selectedCountries.value.length === 0 ||
                    selectedCountries.value.some((c) => movie.countries && movie.countries.includes(c));

                return genreMatch && yearMatch && ratingMatch && countryMatch;
            });
        });

        // 平均评分
        const averageRating = computed(() => {
            if (filteredMovies.value.length === 0) return 0;

            let validRatings = 0;
            const total = filteredMovies.value.reduce((sum, movie) => {
                let rating = movie.rating;
                if (typeof rating === "string") {
                    rating = parseFloat(rating);
                }

                if (!isNaN(rating)) {
                    validRatings++;
                    return sum + rating;
                }
                return sum;
            }, 0);

            return validRatings > 0 ? total / validRatings : 0;
        });

        // 最常见类型
        const topGenre = computed(() => {
            const genreCount = {};

            filteredMovies.value.forEach((movie) => {
                if (movie.genres) {
                    movie.genres.forEach((genre) => {
                        if (!genreCount[genre]) genreCount[genre] = 0;
                        genreCount[genre]++;
                    });
                }
            });

            if (Object.keys(genreCount).length === 0) return "无";

            let max = 0;
            let maxGenre = "";

            for (const genre in genreCount) {
                if (genreCount[genre] > max) {
                    max = genreCount[genre];
                    maxGenre = genre;
                }
            }

            return maxGenre;
        });

        // 电影年份分布
        const yearDistribution = computed(() => {
            const yearCount = {};

            filteredMovies.value.forEach((movie) => {
                const year = movie.year;
                if (year) {
                    if (!yearCount[year]) yearCount[year] = 0;
                    yearCount[year]++;
                }
            });

            return yearCount;
        });

        // 年份最多的电影数量
        const movieCountByYear = computed(() => {
            const dist = yearDistribution.value;
            let max = 0;

            for (const year in dist) {
                if (dist[year] > max) {
                    max = dist[year];
                }
            }

            return max;
        });

        // TOP年份
        const topYear = computed(() => {
            const dist = yearDistribution.value;
            let max = 0;
            let maxYear = "N/A";

            for (const year in dist) {
                if (dist[year] > max) {
                    max = dist[year];
                    maxYear = year;
                }
            }

            return maxYear;
        });

        // 导演影响力数据
        const directorData = computed(() => {
            // 改进的导演影响力计算
            const directorMap = {};
            movies.value.forEach((movie) => {
                if (movie.directors) {
                    movie.directors.forEach((dir) => {
                        if (!directorMap[dir]) directorMap[dir] = { count: 0, totalRating: 0 };
                        directorMap[dir].count++;
                        directorMap[dir].totalRating += parseFloat(movie.rating);
                    });
                }
            });

            return Object.entries(directorMap)
                .filter(([_, data]) => data.count >= 2) // 只包含有2部以上作品的导演
                .map(([name, data]) => {
                    // 改进后的公式 - 加入评分加权和标准化
                    const avgRating = data.totalRating / data.count;
                    const influence = (avgRating * 0.8 + Math.log(data.count + 1) * 0.2) * 10;

                    return {
                        name,
                        influence,
                        avgRating,
                        movieCount: data.count,
                    };
                })
                .sort((a, b) => b.influence - a.influence)
                .slice(0, 15);
        });

        // 重置筛选条件
        const resetFilters = () => {
            selectedGenres.value = [];
            yearRange.value = [1990, 2023];
            minRating.value = 0.0;
            selectedCountries.value = [];
        };

        // 初始化类型图表
        const initGenreChart = () => {
            if (!genreChartRef.value) return;

            const genreCount = {};
            movies.value.forEach((movie) => {
                if (movie.genres) {
                    movie.genres.forEach((genre) => {
                        if (!genreCount[genre]) genreCount[genre] = 0;
                        genreCount[genre]++;
                    });
                }
            });

            const sortedGenres = Object.entries(genreCount)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 15);

            const genreNames = sortedGenres.map((item) => item[0]);
            const genreCounts = sortedGenres.map((item) => item[1]);

            const chart = echarts.init(genreChartRef.value);
            const option = {
                tooltip: {
                    trigger: "axis",
                    axisPointer: { type: "shadow" },
                },
                title: {
                    text: "电影类型分布 TOP15",
                    left: "center",
                },
                xAxis: {
                    type: "category",
                    data: genreNames,
                    axisLabel: {
                        interval: 0,
                        rotate: 30,
                    },
                },
                yAxis: {
                    type: "value",
                    name: "电影数量",
                },
                series: [
                    {
                        type: "bar",
                        data: genreCounts,
                        itemStyle: {
                            color: function (params) {
                                const colors = ["#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de"];
                                return colors[params.dataIndex % colors.length];
                            },
                        },
                    },
                ],
            };

            chart.setOption(option);

            window.addEventListener("resize", () => {
                chart.resize();
            });
        };

        // 初始化年份图表
        const initYearChart = () => {
            if (!yearChartRef.value) return;

            const yearCount = {};

            // 先获取所有年份的范围
            let minYear = 3000;
            let maxYear = 1900;

            movies.value.forEach((movie) => {
                if (movie.year && typeof movie.year === "number") {
                    minYear = Math.min(minYear, movie.year);
                    maxYear = Math.max(maxYear, movie.year);
                }
            });

            // 确保有合理的年份范围
            if (minYear > maxYear || minYear === 3000) {
                minYear = 1990;
                maxYear = new Date().getFullYear();
            }

            // 计算合适的年代间隔，确保数据分布更均匀
            const yearSpan = Math.ceil((maxYear - minYear) / 10); // 尝试分成约10个区间

            // 初始化所有年代区间
            for (let year = minYear; year <= maxYear; year += yearSpan) {
                const yearLabel = `${year}-${Math.min(year + yearSpan - 1, maxYear)}`;
                yearCount[yearLabel] = 0;
            }

            // 统计每个年代的电影数量
            movies.value.forEach((movie) => {
                if (movie.year && typeof movie.year === "number") {
                    const yearGroup = minYear + Math.floor((movie.year - minYear) / yearSpan) * yearSpan;
                    const yearLabel = `${yearGroup}-${Math.min(yearGroup + yearSpan - 1, maxYear)}`;

                    if (yearCount[yearLabel] !== undefined) {
                        yearCount[yearLabel]++;
                    }
                }
            });

            const decades = Object.keys(yearCount);
            const counts = decades.map((decade) => yearCount[decade]);

            const chart = echarts.init(yearChartRef.value);
            const option = {
                tooltip: {
                    trigger: "axis",
                    axisPointer: { type: "shadow" },
                    formatter: function (params) {
                        const yearRange = params[0].name;
                        const count = params[0].value;
                        return `${yearRange}年<br/>电影数量: ${count}部`;
                    },
                },
                title: {
                    text: "电影年代分布",
                    left: "center",
                },
                xAxis: {
                    type: "category",
                    data: decades,
                    axisLabel: {
                        interval: 0,
                        rotate: 30,
                    },
                },
                yAxis: {
                    type: "value",
                    name: "电影数量",
                },
                series: [
                    {
                        type: "bar",
                        data: counts,
                        itemStyle: {
                            color: "#73c0de",
                        },
                        label: {
                            show: true,
                            position: "top",
                            formatter: "{c}",
                        },
                    },
                    {
                        type: "line",
                        data: counts,
                        smooth: true,
                        itemStyle: {
                            color: "#ee6666",
                        },
                        lineStyle: {
                            width: 2,
                        },
                        symbol: "circle",
                        symbolSize: 8,
                    },
                ],
            };

            chart.setOption(option);

            window.addEventListener("resize", () => {
                chart.resize();
            });
        };

        onMounted(() => {
            // 监听视图变化，初始化图表
            watch(showAnalysisView, (newValue) => {
                if (newValue) {
                    nextTick(() => {
                        initGenreChart();
                        initYearChart();
                    });
                }
            });
        });

        return {
            movies,
            selectedGenres,
            yearRange,
            minRating,
            selectedCountries,
            filteredMovies,
            genres,
            countries,
            directors,
            showAnalysisView,
            resetFilters,
            averageRating,
            topGenre,
            movieCountByYear,
            topYear,
            directorData,
            genreChartRef,
            yearChartRef,
        };
    },
};
</script>

<style>
.home-view {
    min-height: 100vh;
    background-color: #f5f7fa;
}

.el-header {
    background-color: #fff;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    padding: 0 20px;
}

.header-content {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.header-content h1 {
    margin: 0;
    font-size: 24px;
    color: #333;
}

.filter-panel {
    margin-bottom: 20px;
}

.filter-card {
    margin-bottom: 20px;
}

.movie-stats {
    margin-bottom: 20px;
}

.stat-card {
    text-align: center;
    padding: 15px;
}

.stat-number {
    font-size: 28px;
    font-weight: bold;
    color: #409eff;
    margin-bottom: 5px;
}

.stat-label {
    color: #666;
    font-size: 14px;
}

.genre-chart,
.year-chart {
    height: 400px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.genre-analysis,
.year-analysis {
    margin-top: 20px;
    margin-bottom: 20px;
}
</style>
